/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TelaEmpresas.java
 *
 * Created on 07/11/2010, 16:16:25
 */
package asfabdesk.apresentacao;

import asfabdesk.dominio.Data;
import asfabdesk.dominio.EmpresaConveniada;
import asfabdesk.dominio.TipoServico;
import asfabdesk.presistencia.DAO;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JInternalFrame;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Mathias
 */
public class TelaEmpresas extends javax.swing.JInternalFrame {

    private List<EmpresaConveniada> empresas = null;

    /** Creates new form TelaEmpresas */
    public TelaEmpresas() throws SQLException {
        initComponents();
        configurarTela();
    }

    public void configurarTela() throws SQLException {
        configurarComboServico();
    }

    public void abrirIFrame(JInternalFrame janela) {
        for (JInternalFrame j : TelaPrincipal.desktop.getAllFrames()) {
            if (janela.getClass() == j.getClass()) {
                j.moveToFront();
                return;
            }
        }
        TelaPrincipal.desktop.add(janela);
        janela.setVisible(true);
    }

    public void configurarComboServico() throws SQLException {
        comboServico.addItem("");
        comboServico.setSelectedItem("");
        java.util.List servicos = (new DAO()).listar(TipoServico.class);
        for (int i = 0; i < servicos.size(); i++) {
            String descricao = ((TipoServico) servicos.get(i)).getDescricao();
            comboServico.addItem(descricao);
        }
    }

    private class ModeloEmpresa extends DefaultTableModel {

        private List<EmpresaConveniada> lista;
        private String[] campos = new String[]{"ID", "Nome Fantasia", "Razão Social", "Tipo Serviço", "Data Cad.", "Ativo"};

        public ModeloEmpresa(List<EmpresaConveniada> list) {
            lista = list;
        }

        public ModeloEmpresa() {
        }

        public EmpresaConveniada getEmpresa(int index) {
            return lista.get(index);
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }

        @Override
        public Object getValueAt(int row, int column) {
            EmpresaConveniada empresa = lista.get(row);


            switch (column) {
                case 0:
                    return empresa.getId();
                case 1:
                    return empresa.getNomeFantasia();
                case 2:
                    return empresa.getRazaoSocial();
                case 3:
                    return empresa.getTipoServico().getDescricao();
                case 4:
                    return new Data().ConverteDataDateStringBra(empresa.getDataCadastro());
                case 5:
                    return empresa.isAtivo();
                default:
                    return null;
            }
        }

        @Override
        public int getRowCount() {
            return lista == null ? 0 : lista.size();
        }

        @Override
        public int getColumnCount() {
            return campos.length;
        }

        @Override
        public String getColumnName(int column) {
            return campos[column];
        }

        @Override
//         método para o campo boolean (ativo)
        public Class<?> getColumnClass(int column) {
            if (column == 5) {
                return Boolean.class;
            }
            return super.getColumnClass(column);
        }
    }

    public void buscaPorFiltroUnico() {
        if (comboFiltro.getSelectedIndex() == 0) {
            empresas = new DAO().listar(EmpresaConveniada.class, "EmpresaPorNomeFantasia", "%" + txtBusca.getText().toUpperCase() + "%");
        } else if (comboFiltro.getSelectedIndex() == 1) {
            empresas = new DAO().listar(EmpresaConveniada.class, "EmpresaPorRazaoSocial", "%" + txtBusca.getText().toUpperCase() + "%");
        } else if (comboFiltro.getSelectedIndex() == 2) {
            empresas = new DAO().listar(EmpresaConveniada.class, "EmpresaPorCnpj", "%" + txtBusca.getText().toUpperCase() + "%");
        } else if (comboFiltro.getSelectedIndex() == 3) {
            empresas = new DAO().listar(EmpresaConveniada.class, "EmpresaPorCidade", "%" + txtBusca.getText().toUpperCase() + "%");
        } else if (comboFiltro.getSelectedIndex() == 4) {
            empresas = new DAO().listar(EmpresaConveniada.class, "EmpresaPorNomeContato", "%" + txtBusca.getText().toUpperCase() + "%");
        }
        tabelaResultado.setModel(new ModeloEmpresa(empresas));
    }

    public void buscaPorFiltroComposto() throws SQLException {
        //combinações de EMPRESAS ativos
        if (comboServico.getSelectedIndex() == 0 && comboStatus.getSelectedIndex() == 0) {
            listarTodosAtivo();
        } else if (comboServico.getSelectedIndex() > 0 && comboStatus.getSelectedIndex() == 0) {
            listarPorTipoServicoAtivo();
        } // combinações de Convenios Inativos
        else if (comboServico.getSelectedIndex() == 0 && comboStatus.getSelectedIndex() == 1) {
            listarTodosInativo();
        } else if (comboServico.getSelectedIndex() > 0 && comboStatus.getSelectedIndex() == 1) {
            listarPorTipoServicoInativo();
        } // combinações de Convenios Ativos e Inativos
        else if (comboServico.getSelectedIndex() == 0 && comboStatus.getSelectedIndex() == 2) {
            listarTodos();
        } else if (comboServico.getSelectedIndex() > 0 && comboStatus.getSelectedIndex() == 2) {
            listarPorTipoServico();
        }
    }

    //####### TIPOS DE BUSCAS POR FILTROS COMPOSTOS ##########
    // listagens por Status = AMBOS #############################################################################################################
    public void listarTodos() {
        empresas = new DAO().listar(EmpresaConveniada.class);
        tabelaResultado.setModel(new ModeloEmpresa(empresas));
    }

    public void listarPorTipoServico() {
        TipoServico servico = new DAO().localizar(TipoServico.class, "TipoServicoPorNome", comboServico.getSelectedItem().toString());
        empresas = new DAO().listar(EmpresaConveniada.class, "EmpresasPorTipoServico", servico);
        tabelaResultado.setModel(new ModeloEmpresa(empresas));
    }

    // listagens por Status = ATIVO #############################################################################################################
    public void listarTodosAtivo() {
        empresas = new DAO().listar(EmpresaConveniada.class, "EmpresasPorStatus", true);
        tabelaResultado.setModel(new ModeloEmpresa(empresas));
    }

    public void listarPorTipoServicoAtivo() {
        TipoServico servico = new DAO().localizar(TipoServico.class, "TipoServicoPorNome", comboServico.getSelectedItem().toString());
        empresas = new DAO().listar(EmpresaConveniada.class, "EmpresasPorTipoServicoStatus", servico, true);
        tabelaResultado.setModel(new ModeloEmpresa(empresas));
    }

    // listagens por Status = INATIVO #############################################################################################################
    public void listarTodosInativo() {
        empresas = new DAO().listar(EmpresaConveniada.class, "EmpresasPorStatus", false);
        tabelaResultado.setModel(new ModeloEmpresa(empresas));
    }

    public void listarPorTipoServicoInativo() {
        TipoServico servico = new DAO().localizar(TipoServico.class, "TipoServicoPorNome", comboServico.getSelectedItem().toString());
        empresas = new DAO().listar(EmpresaConveniada.class, "EmpresasPorTipoServicoStatus", servico, false);
        tabelaResultado.setModel(new ModeloEmpresa(empresas));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        comboServico = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        comboStatus = new javax.swing.JComboBox();
        btnFiltrar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        comboFiltro = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();
        txtBusca = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaResultado = new javax.swing.JTable();
        bfInferior = new javax.swing.JToolBar();
        btnImprimir = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(asfabdesk.apresentacao.AsfabDeskApp.class).getContext().getResourceMap(TelaEmpresas.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel1.setBackground(resourceMap.getColor("jPanel1.background")); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jPanel2.setBackground(resourceMap.getColor("jPanel2.background")); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setIcon(resourceMap.getIcon("jLabel1.icon")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        jPanel2.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 0, -1, -1));

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N
        jPanel2.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, -1, -1));

        comboServico.setName("comboServico"); // NOI18N
        jPanel2.add(comboServico, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 160, -1));

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N
        jPanel2.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 20, -1, -1));

        comboStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ativo", "Inativo", "Ambos" }));
        comboStatus.setName("comboStatus"); // NOI18N
        jPanel2.add(comboStatus, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 40, 60, -1));

        btnFiltrar.setForeground(resourceMap.getColor("btnFiltrar.foreground")); // NOI18N
        btnFiltrar.setText(resourceMap.getString("btnFiltrar.text")); // NOI18N
        btnFiltrar.setName("btnFiltrar"); // NOI18N
        btnFiltrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFiltrarActionPerformed(evt);
            }
        });
        jPanel2.add(btnFiltrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 40, -1, -1));

        jPanel3.setBackground(resourceMap.getColor("jPanel3.background")); // NOI18N
        jPanel3.setName("jPanel3"); // NOI18N
        jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        comboFiltro.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nome Fantasia", "Razão Social", "CNPJ", "Cidade", "Nome Contato" }));
        comboFiltro.setName("comboFiltro"); // NOI18N
        jPanel3.add(comboFiltro, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 12, 147, -1));

        jButton2.setForeground(resourceMap.getColor("jButton2.foreground")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(427, 11, -1, -1));

        txtBusca.setText(resourceMap.getString("txtBusca.text")); // NOI18N
        txtBusca.setName("txtBusca"); // NOI18N
        txtBusca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtBuscaActionPerformed(evt);
            }
        });
        jPanel3.add(txtBusca, new org.netbeans.lib.awtextra.AbsoluteConstraints(163, 12, 260, -1));

        jLabel5.setIcon(resourceMap.getIcon("jLabel5.icon")); // NOI18N
        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N
        jPanel3.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 530, 20));

        jPanel4.setBackground(resourceMap.getColor("jPanel4.background")); // NOI18N
        jPanel4.setName("jPanel4"); // NOI18N
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tabelaResultado.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Nome Fantasia", "Razão Social", "Tipo Serviço", "Data Cad.", "Ativo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaResultado.setName("tabelaResultado"); // NOI18N
        jScrollPane1.setViewportView(tabelaResultado);
        tabelaResultado.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tabelaResultado.columnModel.title0")); // NOI18N
        tabelaResultado.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tabelaResultado.columnModel.title1")); // NOI18N
        tabelaResultado.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("tabelaResultado.columnModel.title2")); // NOI18N
        tabelaResultado.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("tabelaResultado.columnModel.title3")); // NOI18N
        tabelaResultado.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("tabelaResultado.columnModel.title4")); // NOI18N
        tabelaResultado.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("tabelaResultado.columnModel.title5")); // NOI18N

        jPanel4.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 26, 510, 200));

        bfInferior.setFloatable(false);
        bfInferior.setName("bfInferior"); // NOI18N
        bfInferior.setOpaque(false);

        btnImprimir.setForeground(resourceMap.getColor("btnImprimir.foreground")); // NOI18N
        btnImprimir.setIcon(resourceMap.getIcon("btnImprimir.icon")); // NOI18N
        btnImprimir.setText(resourceMap.getString("btnImprimir.text")); // NOI18N
        btnImprimir.setEnabled(false);
        btnImprimir.setFocusable(false);
        btnImprimir.setMaximumSize(new java.awt.Dimension(80, 33));
        btnImprimir.setMinimumSize(new java.awt.Dimension(80, 33));
        btnImprimir.setName("btnImprimir"); // NOI18N
        btnImprimir.setOpaque(false);
        btnImprimir.setPreferredSize(new java.awt.Dimension(67, 33));
        bfInferior.add(btnImprimir);

        btnNovo.setForeground(resourceMap.getColor("btnNovo.foreground")); // NOI18N
        btnNovo.setIcon(resourceMap.getIcon("btnNovo.icon")); // NOI18N
        btnNovo.setText(resourceMap.getString("btnNovo.text")); // NOI18N
        btnNovo.setFocusable(false);
        btnNovo.setName("btnNovo"); // NOI18N
        btnNovo.setOpaque(false);
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });
        bfInferior.add(btnNovo);

        jPanel4.add(bfInferior, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 230, 510, -1));

        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setForeground(resourceMap.getColor("jLabel3.foreground")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N
        jPanel4.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, -1, -1));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 531, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnFiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFiltrarActionPerformed
         try {
            buscaPorFiltroComposto();
        } catch (SQLException ex) {
            Logger.getLogger(TelaEmpresas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnFiltrarActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
       buscaPorFiltroUnico();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void txtBuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBuscaActionPerformed
       buscaPorFiltroUnico();
    }//GEN-LAST:event_txtBuscaActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        try {
            abrirIFrame(new TelaEmpresa());
        } catch (SQLException ex) {
            Logger.getLogger(TelaEmpresas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnNovoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToolBar bfInferior;
    private javax.swing.JButton btnFiltrar;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JComboBox comboFiltro;
    private javax.swing.JComboBox comboServico;
    private javax.swing.JComboBox comboStatus;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabelaResultado;
    private javax.swing.JTextField txtBusca;
    // End of variables declaration//GEN-END:variables
}
